﻿/***************************
* 1.数据初始化
****************************/

//初始化定位 每五分钟取定位一次
var time = new Date().getTime();
var oldtime = 0;
if (iss_localStorage.get("yuqing_location_time") != "") {
    oldtime = parseInt(iss_localStorage.get("yuqing_location_time"))
}
if (time - oldtime > 5 * 60 * 1000) {
    ISS.utils.initLocation();
} else {
    if (iss_localStorage.get("yuqing_longitude") == "" || iss_localStorage.get("yuqing_latitude") == "") {
        ISS.utils.initLocation();
    }
}

// 初始化Url数据
var isLoginOut = iss_localStorage.get("yuqing_isLoginOut");
if (isLoginOut != "false" || iss_localStorage.get("yuqing_appOpenId") == "" || iss_localStorage.get("yuqing_appAccount") == "") {
    InitData();
}

//初始化访问
function InitData() {

    //var appAccount = "b760689cb63a4a92834d6f14173bc293";
    var appAccount = ISS.utils.getParameter("Account");
    if (appAccount == "") {
        iss_localStorage.set("yuqing_appAccount", "b760689cb63a4a92834d6f14173bc293");
        appAccount = "b760689cb63a4a92834d6f14173bc293";
    }
    //var appCode = "0311ZVsi0nqHvj11E9ui0SEUsi01ZVsV";
    var appCode = ISS.utils.getParameter("code");
    var appPage = ISS.utils.getParameter("page");
    // Account
    if (appAccount == undefined || appAccount == "" || appAccount == null) {
        return;
    }
    iss_localStorage.set("yuqing_appAccount", appAccount);
    // Code
    if (appCode == undefined || appCode == "" || appCode == null) {
        return;
    }
    iss_localStorage.set("yuqing_appCode", appCode);
    // OpenId
    var appOpenId = iss_localStorage.get("yuqing_appOpenId");
    if (appOpenId != undefined && appOpenId != "" && appOpenId != null) {
        GetUserId()
        return;
    }
    // Post
    GetOpenId(appAccount, appCode, function () {
        GetUserId();
        if (appPage != undefined && appPage != "") {
            //mainView.router.reloadPage(appPage);
        }
    });
};

/*
发送用户消息
*/
function SendTemplateMessage(messageType, url, jsonData, callback) {
    if (messageType && jsonData) {
        var openid = iss_localStorage.get("yuqing_appOpenId");
        var accountGuid = iss_localStorage.get("yuqing_appAccount");
        // JSON
        var conditionParams = JSON.stringify({
            messageType: messageType,
            AccountGuid: accountGuid,
            OpenId: openid,
            url: url,
            jsonData: jsonData
        });
        // myApp.showPreloader();
        $$.ajax({
            url: ISS_Constants.Url.const_weixin_TemplateMessage_send,
            data: { "conditionParm": conditionParams },
            crossDomain: true,
            dataType: "json",
            success: function (data, status) {
                //                if (data && data.success && data.datas) {
                /** 就算发送消息失败，也要执行callback **/
                if (data && data.success) {
                    // myApp.hidePreloader();
                    if (callback) {
                        callback();
                    }
                }
            },
            error: function (xhr, status) {
                myApp.hidePreloader();
                console.log("ajax error!");
            }
        });
    }
};

/*
* 获取OpenId
*/
function GetOpenId(appAccount, appCode, callback) {
    // 调取
    if (appAccount && appCode) {
        // 清空数据
        iss_localStorage.set("yuqing_appOpenId", "");
        iss_localStorage.set("yuqing_appUserId", "");
        // 获取OpenId
        $$.ajax({
            url: ISS_Constants.Url.const_weixin_openid,
            data: { "action": "1", "conditionParm": "{\"AccountGuid\":\"" + appAccount + "\",\"Code\":\"" + appCode + "\"}" },
            crossDomain: true,
            dataType: "json",
            success: function (data, status) {
                if (data && data.success && data.datas) {
                    var datas = data.datas;
                    if (datas.OAuth.err) {
                        //myApp.alert(datas.OAuth.errcode + "," + datas.OAuth.errmsg);
                        myApp.alert("获取微信用户失败，请尝试刷新");
                        return;
                    }

                    // 设置OpenId
                    var appOpenId = datas.OpenId;
                    iss_localStorage.set("yuqing_appOpenId", appOpenId);

                    if (callback) {
                        callback();
                    }
                }
            },
            error: function (xhr, status) {
                console.log("ajax error!");
            }
        });  // end openid
    }
};

/*
* 获取平台用户ID
*/
function GetUserId(callback) {
    var appAccount = iss_localStorage.get("yuqing_appAccount"); // 全局变量
    var appOpenId = iss_localStorage.get("yuqing_appOpenId"); // 全局变量
    // 调取
    if (appAccount && appOpenId) {
        iss_localStorage.set("yuqing_appUserId", "");
        $$.ajax({
            url: ISS_Constants.Url.const_weixin_userinfo,
            async: false,
            data: { "action": "8", "conditionParm": "{\"AccountGuid\":\"" + appAccount + "\",\"OpenId\":\"" + appOpenId + "\"}" },
            crossDomain: true,
            dataType: "json",
            success: function (data, status) {
                if (data && data.success) {
                    // 设置 UserId
                    var appUserId = "";
                    if (data.datas && data.datas != null && data.datas != "") {
                        appUserId = data.datas;

                        var getUser = JSON.stringify({
                            type: 13,
                            user: { "ID": appUserId }
                        });

                        $$.ajax({
                            url: ISS_Constants.Url.defaulturl + ISS_Constants.serviceName.USERINFO,
                            data: { content: getUser },
                            dataType: "jsonp",
                            method: "POST",
                            success: function (data, status) {
                                data = JSON.parse(data);
                                if (data && data.status == "0") {
                                    var phone = data.results.phoneNumber;
                                    iss_localStorage.set("yuqing_appPhone", phone);
                                }
                            }
                        });
                    }
                    iss_localStorage.set("yuqing_appUserId", appUserId);

                    if (callback) {
                        callback();
                    }
                }
            },
            error: function (xhr, status) {
                console.log("ajax error!");
            }
        }); // end openid
    }
};

/*
* 同步平台用户ID
*/
function UpdateUserId(UserId, msg, err) {
    var openid = iss_localStorage.get("yuqing_appOpenId"); // 全局变量
    $$.ajax({
        url: ISS_Constants.Url.const_weixin_userinfo,
        data: { "action": "9", "conditionParm": "{\"OpenId\":\"" + openid + "\",\"UserId\":\"" + UserId + "\"}" },
        crossDomain: true,
        dataType: "json",
        async: false,
        success: function (data, status) {
            if (data && data.success) {
                // 设置 UserId
                var appUserId = UserId;
                iss_localStorage.set("yuqing_appUserId", appUserId);

                // 刷新页面
                var index = window.location.href.indexOf("#!/");
                if (index > -1) {
                    var url = window.location.href.substr(index + 3); // #!/url
                    mainView.router.reloadPage(url);
                }
                if (msg && msg != "") {
                    myApp.alert(msg);
                }
                return true;
            }
        },
        error: function (xhr, status) { }
    });   // end ajax
};

/*
* 同步WAP_User用户
*/
function SaveWapUser(wapuser) {
    var result;
    var condition = JSON.stringify({
        WapUserGuid: "",
        UserId: wapuser.ID,
        NickName: wapuser.nickname,
        Name: wapuser.name,
        Phone: wapuser.phoneNumber,
        Email: wapuser.email,
        Sex: wapuser.sex,
        Birthday: wapuser.birthday,
        City: wapuser.city,
        CreateTime: wapuser.createTime,
        IsDelete: wapuser.status
    });
    $$.ajax({
        url: ISS_Constants.Url.const_weixin_wapuser_save,
        data: { "conditionParm": condition },
        async: false,
        crossDomain: true,
        method: "POST",
        success: function (data, status) {
            data = JSON.parse(data);
            if (data && data.success == true && data.msg == "") {
                result = true;
            }
            else {
                result = false;
            }
        },
        error: function (xhr, status) {
            result = false;
        }
    });
    return result;
}

/*用户登录积分*/
function CheckScore(userid) {
    //当前天数
    var beginDate = new Date();
    var nowy = beginDate.getFullYear(); //当前年
    var nowm = beginDate.getMonth() + 1; //当前月
    if (nowm.toString().length == 1) {
        nowm = '0' + nowm;
    }
    var nowd = beginDate.getDate(); //当前日
    if (nowd.toString().length == 1) {
        nowd = '0' + nowd;
    }
    var mybeginTime = nowy + "-" + nowm + "-" + nowd;
    //返回解雇
    var result = true;
    //参数 
    var _content = JSON.stringify({
        type: 116,
        conditionParams: {
            Page: { PageIndex: 1, PageSize: 10 },
            Search: [{ 'SearchField': 'ExchangeBeginTime', 'ConditionType': '2', 'AndOR': 'and', 'ListSearchValue': [{ 'ItemValue': mybeginTime }] },
            { 'SearchField': 'ExchangeEndTime', 'ConditionType': '2', 'AndOR': 'and', 'ListSearchValue': [{ 'ItemValue': mybeginTime }] },
            { 'SearchField': 'RuleCode', 'ConditionType': '2', 'AndOR': 'and', 'ListSearchValue': [{ 'ItemValue': _userScoreProject }] },
            { 'SearchField': 'UserID', 'ConditionType': '2', 'AndOR': 'and', 'ListSearchValue': [{ 'ItemValue': userid }] }
            ],
            Order: []
        }
    });
    console.log(_content);
    $$.ajax({
        url: ISS_Constants.Url.defaulturl + ISS_Constants.serviceName.USERSCORE,
        data: { "content": _content },
        async: false,
        crossDomain: true,
        method: "POST",
        success: function (data, status) {
            data = JSON.parse(data);
            if (data && data.status == '0' && data.message == '') {
                if (data.total > 0) {
                    return true;
                } else {
                    result = SignScore(userid);
                }
            }
            else {
                result = false;
            }
        },
        error: function (xhr, status) {
            result = false;
        }
    });
    return result;
};

function SignScore(userid) {
    //当前天数
    var beginDate = new Date();
    var nowy = beginDate.getFullYear(); //当前年
    var nowm = beginDate.getMonth() + 1; //当前月
    var nowd = beginDate.getDate(); //当前日
    var mybeginTime = nowy + "-" + nowm + "-" + nowd;
    //返回结果
    var result = true;
    //参数
    var _content = JSON.stringify({
        type: 73,
        scoreExchangeEntity: {
            ChangeType: 1,
            CreateTime: mybeginTime,
            Creator: 1,
            ExchangeTime: mybeginTime,
            ExchangeType: 1,
            Remark: "签到",
            RuleAction: 0,
            RuleCode: _userScoreProject,
            UserID: userid
        }
    });
    $$.ajax({
        url: ISS_Constants.Url.defaulturl + ISS_Constants.serviceName.USERSCORE,
        data: { "content": _content },
        async: false,
        crossDomain: true,
        method: "POST",
        success: function (data, status) {
            data = JSON.parse(data);
            if (data && data.message == "Success!" && data.status == "0") {
                result = true;
            }
            else {
                result = false;
            }
        },
        error: function (xhr, status) {
            result = false;
        }
    });
    return result;
};

/*
* 是否获取公众号
*/
function hasAccount(msg) {
    var message = "当前公众号错误！";
    if (msg) message = msg;
    var account = iss_localStorage.get("yuqing_appAccount"); // 全局变量
    if (account == undefined || account == null || account == "") {
        myApp.alert(message)
        return false;
    };
    return true;
};

/*
* 是否微信登陆
*/
function hasOpenId(msg) {
    var message = "请使用微信登陆！";
    if (msg) message = msg;
    var openid = iss_localStorage.get("yuqing_appOpenId"); // 全局变量
    if (openid == undefined || openid == null || openid == "") {
        myApp.alert(message)
        return false;
    };
    return true;
};

/*
* 是否绑定微信 
*/
function hasUserId(msg) {
    var message = "平台账号未绑定！";
    if (msg) message = msg;
    var userid = iss_localStorage.get("yuqing_appUserId"); // 全局变量
    var isLoginOut = iss_localStorage.get("yuqing_isLoginOut");
    if (isLoginOut != "false") {
        myApp.alert(message);
        return false;
    }
    if (userid == undefined || userid == null || userid == "") {
        myApp.alert(message);
        return false;
    };
    return true;
};

/*
 * 是否绑定微信
 */
function hasUserIdOther(msg) {
    var message = "平台账号未绑定！";
    if (msg) message = msg;
    var userid = iss_localStorage.get("yuqing_appUserId"); // 全局变量
    var isLoginOut = iss_localStorage.get("yuqing_isLoginOut");
    if (isLoginOut != "false") {
        myApp.addNotification({
            additionalClass: "AddLoginClass",
            title: '余庆智慧旅游',
            message: message,
            hold: 2000,
            closeOnClick: true,
        });
        return false;
    }
    if (userid == undefined || userid == null || userid == "") {

        myApp.addNotification({
            additionalClass: "AddLoginClass",
            title: '余庆智慧旅游',
            message: message,
            hold: 2000,
            closeOnClick: true,
        });


        return false;
    };
    return true;
};

/*
 * 是否绑定微信
 */
function hasUserIdNothing() {

    var userid = iss_localStorage.get("yuqing_appUserId"); // 全局变量
    var isLoginOut = iss_localStorage.get("yuqing_isLoginOut");
    if (isLoginOut != "false") {
        return false;
    }
    if (userid == undefined || userid == null || userid == "") {

        return false;
    };
    return true;
};

/*
* 发送验证码
*/
/*
* 返回 -1 ： 手机格式不正确
0  :  发送失败
1  :  发送成功
*/
function SendVerificationCode(appAccount, phoneNumber, callback) {
    var result;
    //验证手机号格式
    if (!ISS.utils.CheckPhone(phoneNumber)) {
        result = "-1";
        if (callback) {
            callback(result);
        }
        return;
    }

    //提交
    var para = JSON.stringify({
        AccountGuid: appAccount,
        VtType: "1",
        PhoneNumber: phoneNumber
    })
    $$.ajax({
        url: ISS_Constants.Url.const_weixin_send_verificationCode,
        timeout: 10000,
        data: { "conditionParm": para },
        async: true,
        crossDomain: true,
        method: "POST",
        success: function (datas, status) {
            data = JSON.parse(datas);
            if (data && data.datas == true) {
                result = "1";
                if (callback) {
                    callback(result);
                }
            }
            else {
                result = "0";
                if (callback) {
                    callback(result);
                }
            }
        },
        error: function (xhr, status) {
            result = "0";
            if (callback) {
                callback(result);
            }
        }
    });
}

/*
* 校验验证码
*/
function CheckVerificationCode(appAccount, phoneNumber, vericode) {
    var result;
    var para = JSON.stringify({
        AccountGuid: appAccount,
        VtType: "1",
        PhoneNumber: phoneNumber,
        VerificationCode: vericode
    });
    $$.ajax({
        url: ISS_Constants.Url.const_weixin_get_verificationCode,
        data: { "conditionParm": para },
        async: false,
        crossDomain: true,
        method: "POST",
        success: function (data, status) {
            data = JSON.parse(data);
            // if (data && data.datas != null && data.datas.PhoneNumber != null) {
            //     result = data.datas.PhoneNumber;
            // } else {
            //     result = null;
            // }
            if (data && data.success == true) {
                result = phoneNumber;
            } else {
                result = null;
            }
        },
        error: function (xhr, status) {
            result = null;
        }
    });
    return phoneNumber;
}

/*
* 根据电话号码到门户查询用户数据
*/
function GetUserInfoByPhone(phoneNumber) {
    var result;
    //查询
    var _content = JSON.stringify({
        type: "13",
        user: { PhoneNumber: phoneNumber }
    });
    $$.ajax({
        url: ISS_Constants.Url.defaulturl + ISS_Constants.serviceName.USERINFO,
        data: { "content": _content },
        async: false,
        crossDomain: true,
        method: "POST",
        success: function (data, status) {
            data = JSON.parse(data);
            if (data && data.results != null) {
                result = data.results;
            } else {
                result = null;
            }

        },
        error: function (xhr, status) {
            result = null;
        }
    });
    return result;
}

/*
* 根据手机号到门户去注册用户
*/
function CreateUser(phoneNumber) {
    var result;
    //查询
    var _content = JSON.stringify({
        type: "11",
        user: {
            PhoneNumber: phoneNumber,
            Email: "",
            Status: 0,
            CreateTime: new Date(),
            NickName: phoneNumber.substring(0, 3) + "****" + phoneNumber.substring(7),
            Pwd: "111111",
            Name: "微信用户" + phoneNumber,
            City: ""
        }
    })
    $$.ajax({
        url: ISS_Constants.Url.defaulturl + ISS_Constants.serviceName.USERINFO,
        data: { "content": _content },
        async: false,
        crossDomain: true,
        method: "POST",
        success: function (data, status) {
            data = JSON.parse(data);
            if (data && data.message == ""
                && data.status == "0"
                && data.results != null) {
                //创建用户成功
                result = data.results;
            }
            else {
                //创建用户失败
                result = null;
            }
        },
        error: function (xhr, status) {
            //创建用户失败
            result = null;
        }
    });
    return result;
}

/*
* 根据手机号到门户去注册用户
*openId:微信用户唯一标识
*accountGuid:公众号唯一标识
*url:当前页面的完整的url
*imageurl:当前页面的第一张图片地址(用途：微信图文消息)
*当前页面的title(用途：微信图文消息)
*当前页面的描述(用途：微信图文消息)
*/
function RecodeLog(openId, accountGuid, url, imageurl, title, describe) {
    var result;
    var _content = JSON.stringify({
        OpenId: openId,
        AccountGuid: accountGuid,
        url: url,
        Image: imageurl,
        Title: title,
        Describe: describe
    })
    $$.ajax({
        url: ISS_Constants.Url.const_wechat_detaillog_add,
        data: { "conditionParm": _content },
        async: false,
        crossDomain: true,
        method: "POST",
        success: function (data, status) {
            data = JSON.parse(data);
            if (data && data.datas != null) {
                result = data.datas;
            } else {
                result = null;
            }
        },
        error: function (xhr, status) {
            result = null;
        }
    });
    return result;
}

/*
* 获取当前用户最新浏览过的的详情页面
*/
function GetUserDetailLog(openId, accountGuid) {
    var result;
    var _content = JSON.stringify({
        OpenId: openId,
        AccountGuid: accountGuid
    })
    $$.ajax({
        url: ISS_Constants.Url.const_wechat_detaillog_get,
        data: { "conditionParm": _content },
        async: false,
        crossDomain: true,
        method: "POST",
        success: function (data, status) {
            data = JSON.parse(data);
            if (data && data.datas != null) {
                result = data.datas;
            } else {
                result = null;
            }
        },
        error: function (xhr, status) {
            result = null;
        }
    });
    return result;
}

function GetLink(AccountGuid, url) {
    var result;
    var _content = JSON.stringify({
        AccountGuid: AccountGuid,
        Redirect_Url: url,
        OpenIdType: 1
    })
    $$.ajax({
        url: ISS_Constants.Url.const_wechat_detaillog_get,
        data: { "conditionParm": _content },
        async: false,
        crossDomain: true,
        method: "POST",
        success: function (data, status) {
            data = JSON.parse(data);
            if (data && data.datas != null) {
                result = data.datas;
            } else {
                result = null;
            }
        },
        error: function (xhr, status) {
            result = null;
        }
    });
    return result;
}

function getDefaultImg(data) {
    if (data.getImage == null || data.getImage == undefined || data.getImage == "") {
        data.getImage = {
            imageFrontUrl: NoPicture(),
            largeImageFrontUrl: NoPicture(),
            middleImageFrontUrl: NoPicture(),
            smallImageFrontUrl: NoPicture(),
            imageList: [{ middleImgSrc: NoPicture() }]
        };
    }
    if (data.getImage.middleImageFrontUrl == null || data.getImage.middleImageFrontUrl == undefined || data.getImage.middleImageFrontUrl == "") {
        data.getImage.middleImageFrontUrl = NoPicture()
    }
    if (data.getImage.imageList == null || data.getImage.imageList == undefined || data.getImage.imageList.length == 0) {
        data.getImage.imageList = [{ middleImgSrc: data.getImage.middleImageFrontUrl }]
    }
    return data;
}

function share(imageurl, title, describe) {
    var obj = new Object();
    obj.AccountGuid = iss_localStorage.get("yuqing_appAccount");
    obj.Redirect_Url = window.location.href;
    obj.OpenIdType = 1;
    var _content = JSON.stringify(obj);

    $$.ajax({
        url: ISS_Constants.Url.const_wechat_share,
        data: { conditionParm: _content },
        crossDomain: true,
        dataType: "json",
        success: function (data, status) {
            if (data.datas) {
                var urlpara = new Object();
                urlpara.appid = data.datas.appId;
                urlpara.timestamp = data.datas.timestamp;
                urlpara.noncestr = data.datas.noncestr;
                urlpara.signature = data.datas.sign;
                urlpara.link = data.datas.wxurl;
                urlpara.img_url = imageurl;
                urlpara.desc = describe;
                urlpara.title = title;
                //图片地址转码,因为图片名称可能存在中文（不能整个地址转码）
                var imgArray = [];
                var index = imageurl.lastIndexOf("\/");
                imgArray[0] = imageurl.substring(0, index + 1);
                imgArray[1] = imageurl.substring(index + 1);
                var encode_imageurl = imgArray[0] + encodeURIComponent(imgArray[1]);
                //转码结束
                wx.config({
                    debug: false,
                    appId: urlpara.appid,
                    timestamp: urlpara.timestamp,
                    nonceStr: urlpara.noncestr,
                    signature: urlpara.signature,
                    jsApiList: [
                        'onMenuShareAppMessage'
                    ]
                });
                wx.error(function (res) {
                    alert(res);
                });
                wx.ready(function () {
                    wx.onMenuShareAppMessage({
                        title: urlpara.title, // 分享标题
                        desc: urlpara.desc, // 分享描述
                        link: urlpara.link, // 分享链接
                        imgUrl: encode_imageurl, // 分享图标
                        success: function () {
                            // 用户确认分享后执行的回调函数
                        },
                        cancel: function () {
                            // 用户取消分享后执行的回调函数
                        }
                    })
                });
            } else {
                myApp.alert(data.msg);
            }
        },
        error: function (xhr, status) { }
    })
}

function wx_config(gn, callback, errorcallback, realurl) {
    // var obj = new Object();
    // obj.AccountGuid = iss_localStorage.get("yuqing_appAccount"); //"b760689cb63a4a92834d6f14173bc293"
    // if (realurl && realurl != '') {
    //     obj.Redirect_Url = realurl;
    // } else {
    //     obj.Redirect_Url = window.location.href; //要转码
    // }
    // obj.OpenIdType = 1;
    // var _content = JSON.stringify(obj);
    // $$.ajax({
    //     url: ISS_Constants.Url.const_wechat_share,
    //     data: { conditionParm: _content },
    //     crossDomain: true,
    //     dataType: "json",
    //     success: function (data, status) {
    //         if (data.datas) {
    //             var urlpara = new Object();
    //             urlpara.appid = data.datas.appId;
    //             urlpara.timestamp = data.datas.timestamp;
    //             urlpara.noncestr = data.datas.noncestr;
    //             urlpara.signature = data.datas.sign;
    //             wx.config({
    //                 debug: false,
    //                 appId: urlpara.appid,
    //                 timestamp: urlpara.timestamp,
    //                 nonceStr: urlpara.noncestr,
    //                 signature: urlpara.signature,
    //                 jsApiList: gn
    //             });
    //             wx.error(function (res) {

    //             });
    //             wx.ready(function (res) {

    //             });
    //             if (errorcallback) {
    //                 //如果非微信进入，而手动给了account，要单独加载
    //                 if (ISS.utils.isWeiXin()) {
    //                     wx.error(errorcallback);
    //                 } else {
    //                     errorcallback();
    //                 }
    //             }

    //             if (callback) {
    //                 //如果非微信进入，而手动给了account，要单独加载
    //                 if (ISS.utils.isWeiXin()) {
    //                     wx.ready(callback);
    //                 } else {
    //                     callback();
    //                 }
    //             }
    //         } else {
    //             //myApp.alert("if.error:" + data.msg);
    //             console.log(data);
    //             errorcallback();
    //         }
    //     },
    //     error: function (xhr, status) {
    //         console.log("ajax.error:" + status);
    //     }
    // })
}

/*
* 格式化评分
*/
function formatScore(data) {
    var result = "3.0";
    if (data == undefined || data == null || data == "") {
        return result;
    }
    var score = parseFloat(data);
    if (score <= 0) {
        return result;
    }
    return score.toFixed(1);
}